<template>
  <div>
    <div
      v-if="showInput"
      class="manage_sels d-flex align-items-center"
      @click.stop="showDialog"
    >
      <span v-if="submitResult.length == 0" class="manage_tips">请选择</span>
      <i
        class="el-select__caret el-input__icon el-icon-arrow-up arrow_up"
        :class="showDia ? 'is-reverse' : ''"
      ></i>
      <div class="my_ipt" v-if="submitResult.length > 0">
        <el-tag
          closable
          size="small"
          type="info"
          @close="clearChooser(index, item, 1)"
          v-for="(item, index) in submitResult"
          :key="index"
          style="margin-right: 6px; margin-bottom: 6px"
        >
          {{ item ? item.realname : "" }}
        </el-tag>
      </div>
    </div>
    <div>
      <el-dialog
        :visible="showDia"
        :append-to-body="true"
        :close-on-click-modal="false"
        :title="title"
        width="1088px"
        @close="handleCancel"
        class="relate_dia"
      >
        <flexbox class="relate-ccontainer" v-loading="loading">
          <div class="relate_l">
            <flexbox class="title">选择员工</flexbox>
            <flexbox class="relatel_content">
              <div class="relatel_l">
                <!-- 左边树 -->
                <el-tree
                  :data="depTreeList"
                  show-checkbox
                  node-key="id"
                  ref="dep_tree"
                  highlight-current
                  :default-checked-keys="chooseArr"
                  :props="defaultProps"
                  @check="handleCheckChange"
                  class="left_tree"
                  :default-expanded-keys="
                    depTreeList[0] ? [depTreeList[0].deptId] : []
                  "
                >
                </el-tree>
              </div>
              <div class="relatel_r">
                <div class="relatelr_t">
                  <el-input
                    placeholder="请输入搜索内容"
                    class="ipt"
                    v-model="filtersPerson"
                    clearable
                    @keyup.enter.native="toSearch"
                  ></el-input>
                  <el-button
                    type="primary"
                    icon="el-icon-search"
                    @click="toSearch"
                    >搜索</el-button
                  >
                </div>
                <div class="relatelr_b">
                  <!-- 中间树 -->
                  <el-tree
                    :data="selectTree"
                    show-checkbox
                    node-key="userId"
                    ref="center_tree"
                    highlight-current
                    default-expand-all
                    :props="default2Props"
                    @check="centerCheckChange"
                    :filter-node-method="filterNode"
                  >
                  </el-tree>
                </div>
              </div>
            </flexbox>
          </div>
          <div class="relate_r">
            <flexbox class="title">
              <span>已选（{{ personSelects.length }}）</span>
              <span class="pointer" @click="clearSelects">清空全部</span>
            </flexbox>
            <div class="relater_content">
              <div
                class="item"
                style="padding: 0; margin: 0; margin-bottom: 8px"
                v-for="(item, index) in personSelects"
                :key="index"
              >
                <el-tag
                  closable
                  type="info"
                  @close="clearChooser(index, item)"
                  color="#F6F7FC"
                >
                  {{ item ? item.realname : "" }}
                </el-tag>
              </div>
            </div>
          </div>
        </flexbox>
        <span slot="footer" class="dialog-footer">
          <el-button @click.native="handleCancel">取消</el-button>
          <el-button type="primary" @click.native="handleConfirm"
            >确定</el-button
          >
        </span>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { queryBaseUserVoList, depListAPI } from "@/api/common";
import { mapGetters } from "vuex";
export default {
  /** 人员选择器*/
  name: "RelateEmpoyee",
  mixins: [],
  props: {
    visible: {
      required: true,
      default: false
    },
    title: {
      type: String,
      default: "选择人员"
    },
    showInput: {
      type: Boolean,
      default: false
    },
    realname: {
      //已选人员名字
      default: ""
    },
    userId: {
      //已选人员id
      default: ""
    },
    // 需要组件来回显字段名称
    isShowName: {
      default: false
    },
    restrictData: [String]
  },
  data() {
    return {
      loading: false,
      deptId: null,
      roleIdList: null,
      chooseArr: [],
      depTreeList: [], // 属性结构部门
      resultDept: [], // 指定的部门数据
      defaultProps: {
        children: "children",
        label: "label"
      },
      default2Props: {
        children: "children",
        label: "realname"
      },
      chooseResult: [], //左树-这次选中的所有子集
      chooseKey: [], //左树-这次选中的所有子集的key
      lastKeys: [], //左树-上次选中的所有子集的key
      selectTree: [], //中间树结构
      personSelects: [], //选择的总人员
      personss: [], //回显过来的人员
      filtersPerson: "",
      showDia: false,
      submitResult: [], //input框内容
      usersList: []
    };
  },
  computed: {
    ...mapGetters(["depAllTreeList", "userAllList"])
  },
  watch: {
    visible(val) {
      if (val) {
        this.showDia = true;
      } else {
        this.showDia = false;
      }
    },
    userId: {
      /**
       * input框-回显已选项
       */
      handler(val) {
        if (val) {
          val = String(val);
          let selArr = val.split(",");
          let selName = this.realname.split(",");
          selArr.forEach((item, index) => {
            if (this.isShowName) {
              // 循环人员数组
              this.userAllList.forEach(userItem => {
                if (item == userItem.userId) {
                  this.$set(this.personSelects, index, {
                    realname: userItem.realname,
                    userId: selArr[index]
                  });
                  this.$set(this.submitResult, index, {
                    realname: userItem.realname,
                    userId: selArr[index]
                  });
                  this.$set(this.personss, index, {
                    realname: userItem.realname,
                    userId: selArr[index]
                  });
                }
              });
            } else {
              this.$set(this.personSelects, index, {
                realname: selName[index]
              });
              this.$set(this.submitResult, index, { realname: selName[index] });
              this.$set(this.personss, index, {
                realname: selName[index],
                userId: selArr[index]
              });
            }
          });
        } else {
          this.personSelects = [];
          this.submitResult = [];
          this.personss = [];
        }
      },
      immediate: true,
      deep: true
    }
  },
  async mounted() {
    // r如果有过滤条件
    if (this.restrictData) {
      const str = JSON.parse(this.restrictData);
      const target = Object.prototype.toString.call(str);
      target === "[object Object]"
        ? (this.deptId = str.deptId)
        : (this.roleIdList = str);
      const res = await depListAPI({
        type: "tree"
      });
      this.depTreeList = res.data.map((item, index) => {
        if (this.deptId) {
          if (item.deptId != this.deptId) {
            // 筛选条件不是顶级
            item.disabled = true;
          }
          // 获取指定的树结构数据
          this.getTreeItem(item.children, this.deptId);
          item.children = [this.resultDept];
        }
        return item;
      });
    } else {
      this.deptId = null;
      this.roleIdList = null;
      this.depTreeList = this.depAllTreeList;
    }
  },
  methods: {
    // 搜索
    toSearch() {
      this.$refs.dep_tree.setCheckedKeys([this.depTreeList[0].deptId]);
      this.$nextTick(() => {
        this.handleCheckChange(1);
      });
    },
    /**
     * 显示弹框
     */
    showDialog() {
      this.showDia = true;
      this.selectTree = [];
      this.chooseResult = [];
      this.chooseKey = [];
      this.lastKeys = [];
      if (this.submitResult && this.submitResult.length > 0) {
        this.personSelects = JSON.parse(JSON.stringify(this.submitResult));
        this.personss = JSON.parse(JSON.stringify(this.submitResult));
      }
      this.$nextTick(() => {
        if (this.$refs.dep_tree) {
          this.$refs.dep_tree.setCheckedKeys([]);
        }
      });
    },
    /**
     * 取差集
     */
    getDifferentArr(allArr, partArr) {
      for (let i = allArr.length - 1; i >= 0; i--) {
        for (let j = 0; j < partArr.length; j++) {
          if (allArr[i].deptId === partArr[j].deptId) {
            allArr.splice(i, 1);
            break;
          }
        }
      }
      return allArr;
    },
    /**
     * 左边树-只显示勾选部门-新
     */
    handleCheckChange(data, checked, indeterminate) {
      if (data != 1) {
        this.filtersPerson = "";
      }
      let allnodes = this.$refs.dep_tree.getCheckedNodes();
      let allkeys = this.$refs.dep_tree.getCheckedKeys();
      let checkdChildren = []; //所有选中的子集
      allnodes.forEach((item, index) => {
        if (item.children) {
          // eachCheck 单个选中的
          let eachCheck = item.children.filter((item2, index2) => {
            return allkeys.includes(item2.deptId);
          });
          if (eachCheck && eachCheck.length > 0) {
            checkdChildren = checkdChildren.concat(eachCheck);
          }
        }
      });
      this.chooseResult = this.getDifferentArr(allnodes, checkdChildren);
      this.chooseKey = this.chooseResult.map(item => item.deptId);
      // 增加
      this.chooseResult.forEach((item, index) => {
        if (!this.lastKeys.includes(item.deptId)) {
          this.loading = true;
          queryBaseUserVoList({
            deptId: item.deptId,
            roleIdList: this.roleIdList
          }).then(res => {
            this.usersList = res.data;
            setTimeout(() => {
              this.loading = false;
            }, 300);
            let addTree = {
              realname: item.name,
              userId: item.id,
              children: res.data
            };
            if (res.data && res.data.length == 0) {
              addTree.disabled = true;
            }
            if (data == 1) {
              //搜索:重置center_tree数据
              let childs = this.usersList.filter(ite => {
                return ite.realname.indexOf(this.filtersPerson) != -1;
              });
              addTree = {
                realname: item.name,
                userId: item.id,
                children: childs
              };
              // addTree.disabled = true;
            }
            this.selectTree = this.selectTree.concat(addTree);
            if (this.$refs.center_tree) {
              this.$nextTick(() => {
                this.$refs.center_tree.setCheckedNodes(this.personSelects);
                if (data == 1) {
                  //搜索
                  this.$refs.center_tree.filter(this.filtersPerson);
                }
              });
            }
          });
        }
      });
      // 删除
      this.lastKeys.forEach((item, index) => {
        if (!this.chooseKey.includes(item)) {
          for (let k = 0; k < this.selectTree.length; k++) {
            if (this.selectTree[k].userId == item) {
              // 删除部门下的人
              // for (let i = 0; i < this.selectTree[k].children.length; i++) {
              //   let _item = this.selectTree[k].children[i].userId;
              //   for (let j = 0; j < this.personSelects.length; j++) {
              //     if (_item == this.personSelects[j].userId) {
              //       this.personSelects.splice(j, 1);
              //     }
              //   }
              // }
              // 删除部门
              this.selectTree.splice(k, 1);
            }
          }
        }
      });
      setTimeout(() => {
        this.lastKeys = JSON.parse(JSON.stringify(this.chooseKey));
      }, 100);
      if (data == 1) {
        //搜索:重置center_tree数据
        if (this.selectTree && this.selectTree.length > 0) {
          let childs = this.usersList.filter(ite => {
            return ite.realname.indexOf(this.filtersPerson) != -1;
          });
          let addTree = {
            realname: this.chooseResult[0].name,
            userId: this.chooseResult[0].id,
            children: childs
          };
          this.selectTree = [addTree];
          this.$nextTick(() => {
            this.$refs.center_tree.setCheckedNodes(this.personSelects);
            this.$refs.center_tree.filter(this.filtersPerson);
          });
        }
      }
    },
    // 回显-取并集
    add(arr, brr) {
      for (let i = 0; i < arr.length; i++) {
        let temp = arr[i].userId;
        for (let j = 0; j < brr.length; j++) {
          if (brr[j].userId == temp) {
            brr.splice(j, 1);
          }
        }
      }
      return arr.concat(brr);
    },
    /**
     * 中间树-勾选
     */
    centerCheckChange(data, k) {
      let selectPers = this.$refs.center_tree.getCheckedNodes(true);
      let selectKeys = this.$refs.center_tree.getCheckedKeys(true);
      if (this.personss && this.personss.length > 0) {
        console.log("这里-");
        let bingji = this.add(selectPers, this.personss);
        this.personSelects = bingji;
        this.personss = bingji;
      } else {
        let idSelects = this.personSelects.map(item => item.userId);
        let isEdd = selectKeys.some(item => !idSelects.includes(item));

        if (isEdd) {
          //增选
          console.log("增选----------------");
          this.personSelects = this.add(selectPers, this.personSelects);
        } else {
          //减选
          console.log("减选----------------");
          if (!data.children) {
            //减选父节点
            this.personSelects.splice(idSelects.indexOf(data.userId), 1);
          } else {
            //减选单个子节点
            data.children.forEach((it, ind) => {
              this.personSelects.forEach((it2, ind2) => {
                if (it2.userId == it.userId) {
                  this.personSelects.splice(ind2, 1);
                }
              });
            });
          }
        }
      }
    },
    /**
     * 删除单个已选人员
     */
    clearChooser(idx, item, type) {
      // if (this.personss && this.personss.length > 0) {
      //   //剔除回显过来的人员
      //   this.personss.forEach((i, ind) => {
      //     if (i.userId == item.userId) {
      //       this.personss.splice(ind, 1);
      //     }
      //   });
      // }
      this.personSelects.splice(idx, 1);
      let personIds = this.personSelects.map(item => item.userId);
      if (this.$refs.center_tree) {
        this.$nextTick(() => {
          this.$refs.center_tree.setCheckedKeys(personIds);
        });
      }
      if (type == 1) {
        //改初始化数据
        this.submitResult.splice(idx, 1);
        let userIds = this.personSelects.map(item => item.userId);
        this.$emit("save", userIds);
      }
    },
    /**
     * 清空所有人员
     */
    clearSelects() {
      this.personSelects = [];
      this.personss = [];
      this.$refs.center_tree.setCheckedNodes([]);
    },
    /**
     * 筛选人员
     */
    filterNode(value, data) {
      if (!value) return true;
      return data.realname.indexOf(value) !== -1;
    },
    /**
     * 关闭弹框
     */
    handleCancel() {
      // this.clearDatas();
      if (!this.showInput) {
        this.clearDatas();
      }
      this.$emit("update:visible", false);
      this.showDia = false;
    },
    /**
     * 点击确定
     */
    handleConfirm() {
      if (this.personSelects.length == 0) {
        this.$message.error("请选择员工");
      } else {
        this.submitResult = JSON.parse(JSON.stringify(this.personSelects));
        let userIds = this.personSelects.map(item => item.userId);
        if (this.showInput) {
          this.showDia = false;
        }
        this.$emit("save", userIds);
      }
    },
    // 清空所有数据
    clearDatas() {
      this.chooseResult = [];
      this.chooseKey = [];
      this.lastKeys = [];
      this.selectTree = [];
      this.personSelects = [];
      this.filtersPerson = "";
      this.$nextTick(() => {
        if (this.$refs.dep_tree) {
          this.$refs.dep_tree.setCheckedNodes([]);
        }
        if (this.$refs.center_tree) {
          this.$refs.center_tree.setCheckedNodes([]);
        }
      });
    },

    /**
     * 获取指定的数结构
     * @param {*} data 树结构
     * @param {*} id 指定的子集id
     */
    getTreeItem(data, id) {
      data.map(item => {
        if (item.deptId == id) {
          this.resultDept = item; // 结果赋值
        } else {
          if (item.children) {
            this.getTreeItem(item.children, id);
          }
        }
      });
    }
  }
};
</script>

<style lang="scss" scoped>
.relate-ccontainer {
  justify-content: space-between;
  .relate_l {
    width: 832px;
    height: 469px;
    background: #ffffff;
    border: 1px solid #eeeeee;
    border-radius: 4px;
    .title {
      width: 100%;
      height: 32px;
      background: #f5f6fb;
      border-radius: 4px;
      padding-left: 15px;
      font-size: 13px;
      color: #333333;
    }
    .relatel_content {
      height: calc(100% - 32px);
      .relatel_l {
        width: 254px;
        border-right: 1px solid #eeeeee;
        height: calc(100% - 20px);
        overflow-y: scroll;
        margin-top: 20px;
        /deep/ .el-tree-node__content {
          height: 42px;
        }
        /deep/ .el-tree-node__label {
          color: #333333 !important;
        }
      }
      .relatel_r {
        flex: 1;
        height: 100%;
        overflow-y: scroll;
        padding: 0 16px;
        .relatelr_t {
          margin: 15px 0;
          .ipt {
            width: 254px;
            margin-right: 16px;
          }
        }
        // 中间树
        .relatelr_b {
          /deep/ .el-tree > .el-tree-node > .el-tree-node__content {
            background: #f5f6fb;
            height: 35px;
            > .el-tree-node__label {
              font-weight: bold;
            }
          }
          /deep/ .el-tree > .el-tree-node > .el-tree-node__children {
            display: flex;
            flex-wrap: wrap;
            margin-top: 10px;
            margin-left: 17px;
            > div {
              min-width: 25% !important;
              > div {
                padding-left: 0 !important;
              }
            }
          }
          /deep/
            .el-tree--highlight-current
            .el-tree-node.is-current
            > .el-tree-node__content {
            background: transparent;
          }
          /deep/ .el-tree-node__label {
            color: #333333;
          }
          /deep/ .el-tree-node__children .el-tree-node {
            margin-bottom: 10px;
          }
          /deep/ .el-tree .el-tree-node {
            margin-bottom: 16px;
          }
          /deep/
            .el-tree
            .is-leaf.el-tree-node__expand-icon.el-icon-caret-right {
            display: none;
          }
          /deep/ .el-checkbox.is-disabled {
            padding-left: 16px !important;
          }
        }
      }
    }
  }
  .relate_r {
    width: 192px;
    height: 469px;
    background: #ffffff;
    border: 1px solid #eeeeee;
    border-radius: 4px;
    .title {
      width: 100%;
      height: 32px;
      background: #f5f6fb;
      border-radius: 4px;
      padding: 0 16px;
      justify-content: space-between;
      span:first-child {
        font-size: 13px;
        color: #333333;
      }
      span:last-child {
        font-size: 12px;
        color: #4d96ff;
      }
    }
    .relater_content {
      height: calc(100% - 32px - 8px);
      overflow-y: scroll;
      padding-left: 16px;
      padding-right: 16px;
      margin-top: 8px;
      .item {
        padding: 0px;
        margin: 0px 0px 8px;
        /deep/ .el-tag {
          width: 160px;
          display: flex;
          align-items: center;
          justify-content: space-between;
          color: #666666;
          padding: 0 16px !important;
          border: none !important;
        }
      }
    }
  }
}
.manage_sels {
  position: relative;
  width: 100%;
  border-radius: 3px;
  border: 1px solid #e6e6e6;
  min-height: 34px;
  padding: 0 6px;
  cursor: pointer;
  .manage_tips {
    position: absolute;
    color: #c0c4cc;
    line-height: 34px;
  }
  .arrow_up {
    position: absolute;
    right: 3px;
    color: #c0c4cc;
    transform: rotateZ(180deg);
  }
  .is-reverse {
    transform: rotateZ(0deg);
  }
}
.my_ipt {
  width: 100%;
  display: flex;
  align-items: center;
  min-height: 34px;
  flex-wrap: wrap;
  padding-top: 6px;
}
.my_ipt /deep/ .el-tag__close {
  background: #c0c4cc;
}
.relate_dia {
  /deep/ .el-dialog__body {
    padding-top: 0 !important;
  }
  /deep/ .el-dialog__header {
    padding: 25px;
  }
}
.left_tree /deep/ .el-tree-node__label{
   overflow: hidden;
   white-space: nowrap;
   text-overflow: ellipsis;
}
</style>
